/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include "record_playback.h"
#include "utils_noncopyable.h"
#include "muxer_mp4_read.h"
#include <atomic>
#include <mutex>
#include <memory>

namespace El {
namespace Record {

class CPlayback : public IPlayback {
    CPlayback(const CPlayback &) = delete;
    CPlayback &operator=(const CPlayback &) = delete;
    CPlayback(CPlayback &&) = delete;
    CPlayback &operator=(CPlayback &&) = delete;

public:
    CPlayback();
    ~CPlayback() override;

    bool config(int32_t ch, uint32_t start, uint32_t end) override;
    bool config(const std::string &path) override;
    bool start(const Proc &proc) override;
    bool stop() override;
    bool pause() override;
    bool resume() override;
    bool seekByTime(uint32_t time) override;
    bool setSpeed(float speed) override;

private:
    void onVideoFrame(const El::Media::MediaFramePtr &frame);
    void onAudioFrame(const El::Media::MediaFramePtr &frame);

private:
    std::atomic<bool> running_{false};
    std::atomic<bool> paused_{false};
    std::atomic<float> speed_{1.0f};
    
    int32_t channel_{0};
    uint32_t startTime_{0};
    uint32_t endTime_{0};
    std::string filePath_;
    
    Proc frameCallback_;
    std::mutex mutex_;
    
    // MP4 reader instance
    std::unique_ptr<El::Muxer::MP4Read> mp4Reader_;
};

} // namespace Record
} // namespace El